<?php
/**
 * 支付宝扫码支付异步回调处理
 * User: gyc
 * Date: 2016/7/1
 * Time: 13:31
 */
class QrpayAction extends CommonAction
{
	/**
	 * 支付宝扫码异步处理
	 */
	public function notify()
	{
		$returnData = $_POST;
		if (!empty($returnData)) {
			// 存储支付返回的数据包
			$insert = array(
				'data' => json_encode($returnData),
				'create_time' => time(),
			);
			D('AlipayQrpayCallBack')->add($insert);

			// 解析订单编号内的模块ID
			$orderSn = $returnData['out_trade_no'];
			$moduleId = substr($orderSn, 14, 3);
			$moduleId = preg_replace('/^0+/', '', $moduleId);

			// 获取对应模块信息
			$mModule = D('Module');
			$moduleInfo = $mModule->getByPk($moduleId);
			/*if(!$moduleInfo || $moduleInfo['status'] != 0){
				// 消息模板通知开发者错误信息
				$this->notifyReponse();
			}*/

			// 获取对应订单
			$mOrder = D($moduleInfo['order_model_name']);
			$orderInfo = $mOrder->getByOrderSn($orderSn);
			/*if(!$orderInfo){
				// 消息模板通知开发者错误信息
				$this->notifyReponse();
			}*/

			$order = $mOrder->where(array('transaction_id' => $returnData['transaction_id'], 'is_pay_notify' => 1))->find();
			if (empty($order)) {
				// 更新支付状态
				$update = array(
					'order_id' => $orderInfo['order_id'],
					'status' => 1,
					'pay_type' => 2,
					'pay_time' => time(),
					'is_pay_notify' => 1,
					'transaction_id' => $returnData['trade_no'],
					'pay_notify_time' => time(),
				);

                //支付宝存在使用集分宝或者红包的情况，一旦使用部分集分宝或者部分红包，支付宝会生成多笔
                $fund_bill_list_arr =  json_decode($returnData['fund_bill_list'],true);
                if($fund_bill_list_arr && count($fund_bill_list_arr)>1) {
                    $amont = 0;
                    $alipay_part_point = 0;
                    $alipay_part_coupon = 0;
                    $update['part_num'] = 0;
                    foreach ($fund_bill_list_arr as $k => $v) {
                        if ($v['fund_channel'] == 'POINT' && $v['amount'] < $returnData['total_amount']) {
                            $amont += $v['amount'];
                            $alipay_part_point = 1;
                        }
                        if ($v['fund_channel'] == 'MCOUPON' && $v['amount'] < $returnData['total_amount']) {
                            $amont += $v['amount'];
                            $alipay_part_coupon = 1;
                        }
                    }
                    //有可能存在使用（集分宝+红包）刚好全额付款的情况，只能算一笔
                    if ($amont == $returnData['total_amount']) {
                        $update['part_num'] = 1;
                        $update['alipay_part_point'] = 1;
                        $update['alipay_part_coupon'] = 1;
                    } elseif ($amont < $returnData['total_amount']) {
                        if ($alipay_part_point) {
                            $update['part_num']++;
                            $update['alipay_part_point'] = 1;
                        }
                        if ($alipay_part_coupon) {
                            $update['part_num']++;
                            $update['alipay_part_coupon'] = 1;
                        }
                    }
                }

				$mOrder->update($update);

				// 平台支付总表插入支付记录
				$mPay = D('Pay');
				$mUser = D('User');
				$update['module_id'] = $moduleId;
				$update['user_id'] = $orderInfo['user_id'] ? $orderInfo['user_id'] : $orderInfo['uid'];
				if ($orderInfo['user_id'] || $orderInfo['uid']) {
					$accountId = $mUser->getFieldByUserId($orderInfo['user_id'] ? $orderInfo['user_id'] : $orderInfo['uid'], 'account_id');
				} else {
					$accountId = $orderInfo['account_id'];
				}
				$update['account_id'] = $accountId ? $accountId : 0;
				$update['order_sn'] = $orderSn;
				$update['goods_amount'] = $orderInfo['goods_amount'];
				$update['order_amount'] = $returnData['receipt_amount'];
				$update['create_time'] = $orderInfo['create_time'];
				$update['create_date'] = date('Y-m-d H:i:s');
				$mPay->update($update);
				echo 'success';
				try {
					// 回调支付成功的方法，执行划拨
					R($moduleInfo['notify_method'], array($orderInfo['order_id'], $accountId));
				} catch (ThinkException $ex) {
					wLog('error-msg:' . $ex->getMessage(), 'exception');
				}
			}
		}
	}
}